package com.sheyu.mall.product.service.spu.impl;

import com.alibaba.fastjson.TypeReference;
import com.sheyu.common.constant.ProductConstant;
import com.sheyu.common.es.SkuEsModel;
import com.sheyu.common.to.SkuHasStockVo;
import com.sheyu.common.to.SkuReductionTo;
import com.sheyu.common.to.SpuBoundTo;
import com.sheyu.common.utils.R;
import com.sheyu.mall.product.entity.attr.AttrEntity;
import com.sheyu.mall.product.entity.attr.ProductAttrValueEntity;
import com.sheyu.mall.product.entity.brand.BrandEntity;
import com.sheyu.mall.product.entity.category.CategoryEntity;
import com.sheyu.mall.product.entity.sku.SkuImagesEntity;
import com.sheyu.mall.product.entity.sku.SkuInfoEntity;
import com.sheyu.mall.product.entity.sku.SkuSaleAttrValueEntity;
import com.sheyu.mall.product.entity.spu.SpuInfoDescEntity;
import com.sheyu.mall.product.entity.spu.SpuInfoEntity;
import com.sheyu.mall.product.feign.CouponFeignService;
import com.sheyu.mall.product.feign.SearchFeignService;
import com.sheyu.mall.product.feign.WareFeignService;
import com.sheyu.mall.product.service.attr.AttrService;
import com.sheyu.mall.product.service.attr.ProductAttrValueService;
import com.sheyu.mall.product.service.brand.BrandService;
import com.sheyu.mall.product.service.category.CategoryService;
import com.sheyu.mall.product.service.sku.SkuImagesService;
import com.sheyu.mall.product.service.sku.SkuInfoService;
import com.sheyu.mall.product.service.sku.SkuSaleAttrValueService;
import com.sheyu.mall.product.service.spu.SpuImagesService;
import com.sheyu.mall.product.service.spu.SpuInfoDescService;
import com.sheyu.mall.product.service.spu.SpuInfoService;
import com.sheyu.mall.product.service.spu.vo.Bounds;
import com.sheyu.mall.product.service.spu.vo.Skus;
import com.sheyu.mall.product.service.spu.vo.SpuResponseVo;
import com.sheyu.mall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sheyu.common.utils.PageUtils;
import com.sheyu.common.utils.Query;

import com.sheyu.mall.product.dao.spu.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;


    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SearchFeignService searchFeignService;

    /**
     * status:
     * key:
     * brandId: 24
     * catelogId: 165
     * page: 1
     * limit: 10
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)){
            wrapper.eq("id",key).or().like("spu_name",key);
        }

        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId)&&Integer.parseInt(brandId)>0){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId)&&Integer.parseInt(catelogId)>0){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuVo(SpuResponseVo spuResponseVo) {
        //1、保存spuinfo的基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuResponseVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //2、保存spu的描述图片：pms_spu_info_desc

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        List<String> desc = spuResponseVo.getDecript();
        spuInfoDescEntity.setDecript(String.join(",",desc));
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescService.saveDesc(spuInfoDescEntity);

        //3、保存spu的图片集pms_spu_images
        List<String> imageUrls = spuResponseVo.getImages();
        spuImagesService.saveImageUrl(spuInfoEntity.getId(),imageUrls);
        //4、保存spu的规格参数：pms_product_attr_value

        List<BaseAttrs> baseAttrs = spuResponseVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveBatch(productAttrValueEntities);
        //5、保存spu的积分信息：gulimall_sms--->sms_spu_bounds
        Bounds bounds  = spuResponseVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        spuBoundTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundTo.setGrowBounds(bounds.getGrowBounds());
        R r = couponFeignService.saveBounds(spuBoundTo);

        if (r.getCode()!=0){
            log.error("远程调用积分信息错误");
        }

        List<Skus> skus = spuResponseVo.getSkus();
        if (skus!=null && skus.size()>0){
            skus.forEach(item->{
                String defaultImg = "";
                for(Images images:item.getImages()){
                    if (images.getDefaultImg()==1){
                        defaultImg = images.getImgUrl();
                    }
                }
                //5、保存sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                //6、保存SkuImagesEntity信息
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map((obj)->{
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(obj.getImgUrl());
                    skuImagesEntity.setDefaultImg(obj.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                List<Attr> attrList = item.getAttr();
                //保存SkuSaleAttrValueEntity信息
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrList.stream().map((obj) -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(obj,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //保存优惠信息，包括会员价
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R rReduction = couponFeignService.saveReduction(skuReductionTo);
                    if (rReduction.getCode()!=0){
                        log.error("满减远程调用失败");
                    }
                }

            });
        }

    }

    /**
     * 商品上架
     * 1、查出当前spuId对应的所有sku信息,品牌的名字
     * @param spuId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void up(Long spuId) {
        //1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        //2、查出当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListforspu(spuId);

        //3、获取对应的属性值
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //4、获取属性值中属于搜索属性的值
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        //转换为Set集合
        Set<Long> idSet = searchAttrIds.stream().collect(Collectors.toSet());

        //给es的索引赋值
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //获取所有的skuId
        List<Long> skuIdList = skuInfoEntities.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        //5、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }

        //6、封装每个sku的信息给es
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfoEntities.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //TODO 7、热度评分。0
            esModel.setHotScore(0L);

            //8、查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandId(brandEntity.getBrandId());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogId(categoryEntity.getCatId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);

            BeanUtils.copyProperties(sku,esModel);

            return esModel;
        }).collect(Collectors.toList());
        //9、发送商品给es保存
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode()==0){
            log.info("远程调用成功");
            baseMapper.updateSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        }else{
            //TODO 重复调用？接口幂等性问题
            log.error("远程调用失败");
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);

        Long spuId = skuInfoEntity.getSpuId();

        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);
        //替换上面的单表查询
//        SpuInfoEntity spuInfoEntity1 = baseMapper.selectSpuInfoByskuIdBySQL(skuId);

        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        spuInfoEntity.setBrandName(brandEntity.getName());
        return spuInfoEntity;
    }
}
